package org.mogu.adapter;

/*
 * Copyright (C) 2011 androd源码工作室
 * 
 * Android实战教程--Android2011QQ
 * 
 * taobao : 
 * mail : androidSource@139.com
 * QQ:    androidSource@139.com
 * 
 */
import java.util.ArrayList;
import java.util.List;

import org.mogu.ContactManagerActivity;
import org.mogu.R;
import org.mogu.control.CustomedImageView;
import org.mogu.control.model.IMUser;
import org.mogu.db.ActiveUserHelper;
import org.mogu.db.DBhelper;
import org.mogu.service.InfoSync;
import org.mogu.staticvalue.Convert;
import org.mogu.tools.HeaderPic;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class FriendExpandableListAdapter extends BaseExpandableListAdapter 
		implements View.OnClickListener{
	 private LayoutInflater mLayoutInflater = null;	
     private  Context context;
 	 public List<String> groups=new ArrayList<String>();
     public List<List<IMUser>> childs=new ArrayList<List<IMUser>>();
     
     ActiveUserHelper auh;
     SQLiteDatabase readdb;
     String code;
     
 	 
 	 private int var=1;
 	 
 	 public void upVar(){
 		 var+=1;
 	 }
 	 
 	public SQLiteDatabase getReaddb() {
		if (readdb == null || !readdb.isOpen()) {
			readdb = auh.getReadableDatabase();
		}
		return readdb;
	}
 	public void close(){
 		if (readdb != null && readdb.isOpen()) {
			readdb.close();
		}
 	}
     /*
      * 构造函数
      * 参数--属于activity
      * */
	 public FriendExpandableListAdapter(Context paramContext,String code){
		 context = paramContext;
		 this.code=code;
		 auh=DBhelper.getDBHelper(context);
		 mLayoutInflater = LayoutInflater.from(context);
		 
    	
			try {
				
					getData();
				//从数据库里取出数据
				
				
				
			} catch (Exception e) {
				e.printStackTrace();
				
				return;
				// TODO: handle exception
			}
    }
	 public void getData(){
		 String[] imUserArr={Convert.uname,code};
		 ArrayList<IMUser> friend=new ArrayList<IMUser>();
		 ArrayList<IMUser> stranger=new ArrayList<IMUser>();
		 IMUser imUser;
		 synchronized (InfoSync.class) {
			 Cursor userCursor = getReaddb().rawQuery(
					 "select code,title,content,replyType,maincode,level,father,lastUpdateTime,id from content where username=? and father=? order by lastUpdateTime desc",
					 imUserArr);
			 userCursor.moveToFirst();
			 while(!userCursor.isAfterLast()){
				 if("1".equals(userCursor.getString(1))){
					 imUser=new IMUser();
					 imUser.setCode(userCursor.getString(0));
					 imUser.setTitle(userCursor.getString(1));
					 imUser.setContent(userCursor.getString(2));
					 imUser.setReplyType(userCursor.getString(3));
					 imUser.setMaincode(userCursor.getString(4));
					 imUser.setLevel(userCursor.getString(5));
					 imUser.setFather(userCursor.getString(6));
					 imUser.setLastUpdateTime(userCursor.getString(7));
					 imUser.setId(userCursor.getInt(8));
					 friend.add(imUser);
				 }else if ("2".equals(userCursor.getString(1))) {
					 imUser=new IMUser();
					 imUser.setCode(userCursor.getString(0));
					 imUser.setTitle(userCursor.getString(1));
					 imUser.setContent(userCursor.getString(2));
					 imUser.setReplyType(userCursor.getString(3));
					 imUser.setMaincode(userCursor.getString(4));
					 imUser.setLevel(userCursor.getString(5));
					 imUser.setFather(userCursor.getString(6));
					 imUser.setLastUpdateTime(userCursor.getString(7));
					 imUser.setId(userCursor.getInt(8));
					 stranger.add(imUser);
				}
				 
				 userCursor.moveToNext();
			 }
			 userCursor.close();
			 close();
		 }
		 groups.clear();
		 childs.clear();
		 groups.add("好友 [ "+friend.size()+" ]");
		 childs.add(friend);
		 groups.add("陌生人 [ "+stranger.size()+" ]");
		 childs.add(stranger);
		 
		 this.notifyDataSetChanged();
	 }
	 
    /*
     * 二级列表对象
     * */
	@Override
	public Object getChild(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return (childs != null)?childs.get(groupPosition).get(childPosition):null;
	}

	/*
	 * 二级列表下标
	 * */
	@Override
	public long getChildId(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return childPosition;
	}

	
	/*
	 * ExpandableListView获取二级列表View对象
	 * getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent)
	 * 参数1--选择的一级列表下标
	 * 参数2--选择的二级列表下标
	 * 参数3--是否最后一个字视图
	 * 参数4--当前视图
	 * 参数5--父视图
	 * 
	 * */
	@Override
	public View getChildView(int groupPosition, int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
			
			View localView = convertView;
			
			//判断当前view视图参数是否为null
		    if (localView == null){
		        //加载一级视图的布局文件
		    	localView = mLayoutInflater.inflate(R.layout.child_list_item, null);
		    }
		    
		    IMUser imUser=(IMUser)getChild(groupPosition, childPosition);
		    
		    /*
		     * 相关控件设置
		     * */
		    //头像
		    ImageView headIcon = (ImageView)localView.findViewById(R.id.headIcon);
		    //在线标识
//		    ImageView buddyStatue = (ImageView)localView.findViewById(R.id.buddyStatue);
		    //昵称
		    TextView name = (TextView)localView.findViewById(R.id.name);
		    //心情
		    TextView info = (TextView)localView.findViewById(R.id.info);
		    //编辑按钮
		    CustomedImageView contextbtn = (CustomedImageView)localView.findViewById(R.id.contextbtn);
		    contextbtn.setImUser(imUser);
		    //设置编辑按钮的单击事件监听器
		    contextbtn.setOnClickListener(this);
		    
		    /*
		     * 设置控件内容
		     * */
//		    TreeNode childItem = (TreeNode)getChild(groupPosition, childPosition);
		    
		    name.setText(imUser.getUnicename());
		    info.setText(imUser.getDesc());
		    String[] imUserArr={Convert.uname,imUser.getCode()};
		    String[] imUserArr2={Convert.uname,imUser.getCode(),"0"};
		    int num=0;
		    int contentid=0;
		    if(imUser.getVar()==var){
		    	num=imUser.getCount();
		    }else{
			    synchronized (InfoSync.class) {
			    	Cursor userCursor = getReaddb().rawQuery(
							 "select contentid from contentread where username=? and code=? ",
							 imUserArr);
					 userCursor.moveToFirst();
					 while(!userCursor.isAfterLast()){
						 contentid=userCursor.getInt(0);
						 userCursor.moveToNext();
						 break;
					 }
					 userCursor.close();
					 imUserArr2[2]=String.valueOf(contentid);
					 userCursor = getReaddb().rawQuery(
							 "select count(*) as num from content where username=? and father=? and id>?",
							 imUserArr2);
					 userCursor.moveToFirst();
					 while(!userCursor.isAfterLast()){
						 num=userCursor.getInt(0);
						 userCursor.moveToNext();
						 break;
					 }
					 userCursor.close();
					 imUser.setCount(num);
					 imUser.setHascount(true);
			    }
			    imUser.setVar(var);
			    
		    }
		    if(num>0){
		    	name.append("( "+num+" 条未读)");
		    }
		    
		    if(imUser.getHeader()==0){
		    	headIcon.setImageResource(R.drawable.moguico);
//		    	buddyStatue.setImageResource(R.drawable.status_offline);
		    }else{
		    	headIcon.setImageResource(HeaderPic.getHeader(imUser.getHeader()));
//		    	buddyStatue.setImageResource(R.drawable.status_online);
		    }
		    
		    //设置视图间距
		    localView.setPadding(0, 0, 0, 0);
		    //获取资源文件对象
		    Drawable localDrawable = context.getResources().getDrawable(R.drawable.highlight_item);
		    //设置视图背景
		    localView.setBackgroundDrawable(localDrawable);
		    
		    
			return localView;
	}


	/*
	 * 二级列表总数
	 * */
	@Override
	public int getChildrenCount(int groupPosition) {
		// TODO Auto-generated method stub
		return (childs != null)?childs.get(groupPosition).size():0;
	}

	/*
	 * 一级列表列表项
	 * */
	@Override
	public Object getGroup(int groupPosition) {
		// TODO Auto-generated method stub
		
		return (groups != null)?groups.get(groupPosition):null;
	}

	/*
	 * 一级列表总数
	 * */
	@Override
	public int getGroupCount() {
		// TODO Auto-generated method stub
		return (groups != null)?groups.size():0;
	}

	@Override
	public long getGroupId(int groupPosition) {
		// TODO Auto-generated method stub
		return groupPosition;
	}

	/*
	 * ExpandableListView获取一级列表View对象
	 * getGroupView(int groupPosition, boolean isExpanded,View paramView, ViewGroup parent)
	 * 参数1--选择的一级列表下标
	 * 参数2--是否展开
	 * 参数3--当前一级列表view对象
	 * 参数4--父类视图
	 * 
	 * */
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View paramView, ViewGroup parent) {
		//定义当前视图view
		View localView  = paramView;
		//判断当前view视图参数是否为null
	    if (localView == null){
	        //加载一级视图的布局文件
	    	localView = mLayoutInflater.inflate(R.layout.contact_group_item, null);
	    }
	    
	    //分组名称
	    TextView name = (TextView)localView.findViewById(R.id.name);
	    //此分组中好友数量
//	    TextView count = (TextView)localView.findViewById(R.id.count);
	    
	    /*
	     * 设置控件内容
	     * */
//	    Map<String,String> groupItem = groups.get(groupPosition);
	    name.setText(groups.get(groupPosition));
//	    count.setText("["+groupItem.get("line")+"/"+groupItem.get("count")+"]");
	    
	    //返回当前视图对象
		return localView;
	}

	@Override
	public boolean hasStableIds() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return true;
	}
	
	/*
	 * 控件单击事件监听器函数
	 * */
	@Override
	public void onClick(View view){
		CustomedImageView image=(CustomedImageView)view;
		Intent mIntent = new Intent(context, ContactManagerActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("iMUser", image.getImUser());
		mIntent.putExtras(bundle);
		context.startActivity(mIntent);
	}

}
